
/**
 * Created by wuye on 2017/12/11.
 */
$(function () {
    $("#jqGrid").jqGrid({
        url: baseURL + 'sys/book/findAllByCondition',
        datatype: "json",
        colModel: [{
                label: 'id',
                name: 'id',
                index: "id",
                width: 25,
                key: true
            },
            {
                label: '书名',
                name: 'bookname',
                width: 75
            },
            {
                label: '作者',
                name: 'authorName',
                width: 75
            },
            {
                label: '所属分类',
                name: 'categoryname',
                width: 40
            },
            /*{
                label: '支付',
                name: 'ispay',
                width: 40,
                formatter: function (value, options, row) {
                    return value === true ?
                        '<span class="label label-danger">是</span>' :
                        '<span class="label label-success">否</span>';
                }
            },*/
            {
                label: '连载',
                name: 'isserialize',
                width: 40,
                formatter: function (value, options, row) {
                    console.log(value)
                    return value === true ?
                        '<span class="label label-danger">是</span>' :
                        '<span class="label label-success">否</span>';
                }
            },
            {
                label: '三界都在看',
                name: 'issanjie',
                width: 40,
                formatter: function (value, options, row) {
                    return value === true ?
                        '<span class="label label-danger">是</span>' :
                        '<span class="label label-success">否</span>';
                }
            },
            {
                label: '中原武侠',
                name: 'iswuxia',
                width: 40,
                formatter: function (value, options, row) {
                    return value === true ?
                        '<span class="label label-danger">是</span>' :
                        '<span class="label label-success">否</span>';
                }
            },
            {
                label: '仙界大陆',
                name: 'isxianjie',
                width: 40,
                formatter: function (value, options, row) {
                    return value === true ?
                        '<span class="label label-danger">是</span>' :
                        '<span class="label label-success">否</span>';
                }
            },
            {
                label: '奇幻世界',
                name: 'isqihuan',
                width: 40,
                formatter: function (value, options, row) {
                    return value === true ?
                        '<span class="label label-danger">是</span>' :
                        '<span class="label label-success">否</span>';
                }
            },
            {
                label: '宫廷侯爵',
                name: 'isgongting',
                width: 40,
                formatter: function (value, options, row) {
                    return value === true ?
                        '<span class="label label-danger">是</span>' :
                        '<span class="label label-success">否</span>';
                }
            },
            {
                label: '现言优选',
                name: 'isxianyan',
                width: 40,
                formatter: function (value, options, row) {
                    return value === true ?
                        '<span class="label label-danger">是</span>' :
                        '<span class="label label-success">否</span>';
                }
            },
            {
                label: '主编精选',
                name: 'isjingxuan',
                width: 40,
                formatter: function (value, options, row) {
                    return value === true ?
                        '<span class="label label-danger">是</span>' :
                        '<span class="label label-success">否</span>';
                }
            },
            {
                label: '热门精选',
                name: 'isremen',
                width: 40,
                formatter: function (value, options, row) {
                    return value === true ?
                        '<span class="label label-danger">是</span>' :
                        '<span class="label label-success">否</span>';
                }
            },
            {
                label: '是否参赛',
                name: 'isGame',
                width: 40,
                formatter: function (value, options, row) {
                    if (value === 0) {
                        return '<span class="label label-primary">未参赛</span>';
                    }
                    if (value === 1) {
                        return '<span class="label label-default">已参赛</span>';
                    }
                }
            },
            {
                label: '类型',
                name: 'origin',
                width: 40,
                formatter: function (value, options, row) {
                    if (value === 0) {
                        return '<span class="label label-warning">本站</span>';
                    }
                    if (value === 1) {
                        return '<span class="label label-primary">原创</span>';
                    }
                    if (value === 2) {
                        return '<span class="label label-info">趣阅</span>';
                    }
                    if (value === 3) {
                        return '<span class="label label-default">寒武</span>';
                    }
                }
            },
            {
                label: '点击量',
                name: 'checknum',
                index: "checknum",
                width: 35
            },
            {
                label: '章节数',
                name: 'sectionNumber',
                index: "sectionNumber",
                width: 35
            },
            {
                label: '创建时间',
                name: 'updatedate',
                index: "updatedate",
                width: 90
            },
            {
                label: '操作',
                name: 'updatedate',
                index: "updatedate",
                width: 100,
                formatter: function (value, options, row) {
                       return '<span class="btn btn-primary checkInfo" mm="'+row.id+'">查看详情</span><span class="btn btn-primary setPrice" style="margin-left: 10px" mm="'+row.id+'" data-name="'+row.bookname+'">定价</span>'
                }
            }
        ],
        viewrecords: true,
        height: 385,
        rowNum: 10,
        rowList: [10, 30, 50],
        rownumbers: true,
        rownumWidth: 25,
        autowidth: true,
        multiselect: true,
        pager: "#jqGridPager",
        jsonReader: {
            root: "page.records",
            page: "page.current",
            total: "page.pages",
            records: "page.total"
        },
        prmNames: {
            page: "page",
            rows: "limit",
            order: "order"
        },
        gridComplete: function () {
            //隐藏grid底部滚动条
            $("#jqGrid").closest(".ui-jqgrid-bdiv").css({
                "overflow-x": "hidden"
            });
            $(".checkInfo").on("click", function(){
                window.location.href = 'bookDetail.html?id='+($(this).attr("mm"))
            });
            $(".setPrice").on("click", function(){
                let bookId=$(this).attr("mm")
                let bookName=$(this).attr("data-name")
                $.get(baseURL + "sys/kwordprice/findAll/" , function (r) {
                    var str='<span>选择每千字收费蝉币：</span><select id="selectMoney">';
                    for(var i of r.data){

                        str+=`<option data-id=${i.id} book-id=${bookId}>${i.price/100}蝉币</option>`
                    }
                    str+='</select>'
                    layer.open({
                        title:bookName+'.图书定价',
                        type: 1,
                        skin: 'layui-layer-rim', //加上边框
                        area: ['420px', '280px'], //宽高
                        content: '<div style="padding: 10px;"><span style="color: red">注</span>：请输入起始收费章节的序号，请务必输入纯阿拉伯数字(如10,25,33...)，不能有小数，然后选择每千字所收蝉币</div>' +
                        '<div style="display: flex;align-items: center;padding: 10px;"><span>起始章节：</span><input placeholder="请输入" id="typingTheNum" style="width: 80%"></div>' +
                        '<div style="padding: 10px">'+str+'</div>' +
                        '<div style="padding: 10px;display: flex;justify-content: flex-end"><button class="btn btn-default" id="closeDivs" style="width: 100px;height: 30px;margin-right: 10px">取消</button><button class="btn btn-success" id="setThePrice" style="width: 100px;height: 30px;">确定</button></div>',
                    });
                });
            });
            $(document).on("click",'#closeDivs',function(){
                layer.closeAll('page')
            });
            $(document).off('click','#setThePrice').on("click",'#setThePrice',function(){
                console.log('oneone')
                let index = layer.load(2, {shade: false}); //0代表加载的风格，支持0-2
                let num=$('#typingTheNum').val();
                let id=$('#selectMoney option:selected').attr('data-id');
                let bookid=$('#selectMoney option:selected').attr('book-id');
                let sfile = new FormData()
                sfile.append('start', Number(num))
                sfile.append('kwordPriceId', id)
                sfile.append('bookid', bookid);


                $.ajax({
                    url: baseURL + '/sys/book/pricing',
                    // $refs: {'tdSection':vm.section,'filetext':this.section.filetext},
                    data: sfile,
                    // headers: {
                    //"Content-Type": "multipart/form-$refs"
                    // "Content-Type": "text/plain;charset=UTF-8"
                    // },
                    cache: false,
                    processData: false,
                    contentType: false,
                    type: 'post',
                    success: function (result) {
                        layer.closeAll('loading')
                        if(result.code === 0){
                            alert(result.msg, function () {
                                window.location.reload();
                            });
                        }else {
                            alert(result.msg);
                        }
                    },
                })
                console.log(num,id,bookid)
            });

        }
    });
});

var setting = {
    data: {
        simpleData: {
            enable: true,
            idKey: "deptId",
            pIdKey: "parentId",
            rootPId: -1
        },
        key: {
            url: "nourl"
        }
    }
};
var ztree;

var vm = new Vue({
    el: '#rrapp',
    data: {
        // 显示添加章节的dom节点
        showDom: 'list',
        q: {
            bookname: null
        },
        showList: true,
        title: null,
        book: {
            issanjie: true,
            iswuxia: true,
            isxianjie: true,
            isqihuan: true,
            isgongting: true,
            isxianyan: true,
            isjingxuan: true,
            isremen: true,
            isserialize: true,
            picurl: null,
            categoryid: '',
            id: null,
            bookname: null,
            ispay: false,
            origin:null,

        },
        
        book2: {
            issanjie: true,
            iswuxia: true,
            isxianjie: true,
            isqihuan: true,
            isgongting: true,
            isxianyan: true,
            isjingxuan: true,
            isremen: true,
            isserialize: true,
            picurl: null,
            categoryid: '',
            id: null,
            bookname: null,
            ispay: false,
            origin:null,

        },
        section: {
            sectionname: null,
            x: null,
            z: null,
        },
        sels: [
            // {value:"1",week:"一"},
            // {value:"2",week:"二"},
            // {value:"3",week:"三"},
            // {value:"4",week:"四"}
        ],
        xels: [
            {value:"0",week:"本站"},
            {value:"1",week:"原创"},
            {value:"2",week:"趣阅"},
            {value:"3",week:"寒武"}
        ],
        vels: [
            {value:"0",week:"未参赛"},
            {value:"1",week:"已参赛"}
        ]
    },
    created: function () {
        $.ajax({
            url: baseURL + 'sys/category/findAll',
            type: "POST",
            contentType: "application/json",
            success: function (result) {
                vm.sels = result.list
            },
            error: function (error) {
                alert('数据加载失败!');
            }
        })
    },
    filters:{
        pic: function(value) {
            if (
                value.backgroundImage === "url(undefined)" ||
                value.backgroundImage == "url()" ||
                value.backgroundImage == "url(null)"
            )
                return { backgroundImage: "url(../../img/zanwu.png" };
            return value;
        },
    },
    methods: {
        getSectionList: function () {
            var id = getSelectedRow();
            if (id == null) {
                return;
            }
            vm.showDom = "sectionList"
            window.location.href = 'section.html?id='+id
        },
        getVolumeList: function () {
            var id = getSelectedRow();
            if (id == null) {
                return;
            }
            vm.showDom = "volumeList"
            window.location.href = 'volume2.html?id='+id
        },
        changeImage: function (e) {
            var file = e.target.files[0]
            var reader = new FileReader()
            var THIS = this
            reader.readAsDataURL(file)
            reader.onload = function (e) {
                // this.result 为图片
                THIS.upload(this.result)
            }
        },
        changeImage1: function (e) {
            var file = e.target.files[0]
            var reader = new FileReader()
            var THIS = this
            reader.readAsDataURL(file)
            reader.onload = function (e) {
                // this.result 为图片
                THIS.upload1(this.result)
            }
        },
        upload: function ($refs) {
            // 上传图片
            var THIS = this;
            if (this.$refs.file.files.length !== 0) {
                var image = new FormData()
                image.append('file', this.$refs.file.files[0])

                $.ajax({
                    url: '/youxiang/api/upload/up',
                    data: image,
                    // headers: {
                    //     "Content-Type": "multipart/form-data"
                    // },
                    cache: false,
                    processData: false,
                    contentType: false,
                    type: 'post',
                    success: function (result) {
                        console.log(result.url);
                        THIS.book.picurl = result.url
                    },
                    error: function (error) {
                        alert('图片上传失败!');
                    }
                })
            }
        },
        upload1: function ($refs) {
            // 上传图片
            var THIS = this;
            if (this.$refs.file1.files.length !== 0) {
                var image = new FormData()
                image.append('file', this.$refs.file1.files[0])

                $.ajax({
                    url: '/youxiang/api/upload/up',
                    data: image,
                    // headers: {
                    //     "Content-Type": "multipart/form-data"
                    // },
                    cache: false,
                    processData: false,
                    contentType: false,
                    type: 'post',
                    success: function (result) {
                        console.log(result.url);
                        THIS.book.picurl = result.url
                    },
                    error: function (error) {
                        alert('图片上传失败!');
                    }
                })
            }
        },
        query: function () {
            vm.reload();
        },
        add: function () {
            vm.showList = false;
            vm.showDom = 'addOrEdit'
            vm.title = "添加新书";
            vm.book = vm.book2;
        },
        add2: function () {
            vm.showList = false;
            vm.showDom = 'addOrEdit2'
            vm.title = "添加新书";
            vm.book = vm.book2;
        },
        updatebook: function () {
            var id = getSelectedRow();
            if (id == null) {
                return;
            }
            vm.showList = false;
            vm.showDom = 'addOrEdit'

            vm.title = "修改书籍";
            vm.getBook(id);
        },
        updatebookbyauthor: function () {
            var id = getSelectedRow();
            if (id == null) {
                return;
            }
            vm.showList = false;
            vm.showDom = 'addOrEdit2'

            vm.title = "修改书籍";
            vm.getBook(id);
        },
        updatesection: function () {
            var id = getSelectedRow();
            if (id == null) {
                return;
            }

            vm.showList = false;
            vm.showDom = 'addSec'

            vm.title = "修改章节";
            // 应该在此处去查询
        },
        del: function () {
            var ids = getSelectedRows();
            if (ids == null) {
                return;
            }
            confirm('删除将清理图书所有数据，确定要删除选中的记录？', function () {
                $.ajax({
                    type: "POST",
                    url: baseURL + "sys/book/delete",
                    contentType: "application/json",
                    data: JSON.stringify(ids),
                    success: function (r) {
                        if (r.code == 0) {
                            alert(r.msg, function () {
                                vm.reload();
                            });
                        } else {
                            alert(r.msg);
                        }
                    }
                });
            });
        },
        cateName: function () {
            vm.showList = true;
            vm.showDom = 'list'
            var page = $("#jqGrid").jqGrid('getGridParam', 'page');
            $("#jqGrid").jqGrid('setGridParam', {
                postData: {
                    'categoryid': this.book.categoryid,
                    'origin' : this.book.origin,
                    'isGame' : this.book.isGame
                },
                page: page
            }).trigger("reloadGrid");
        },
        saveOrUpdate: function (type) {
            /*console.log(type)
            console.log(vm.book)*/
            if(vm.book.id){
                console.log("修改")

            }else {
                console.log("添加")
                var arr;
                if(type){
                    arr=type.split(',');
                    vm.book.origin = arr[0];
                    vm.book.source = arr[1];
                }else {
                    vm.book.origin = type;
                }
            }
            var url = "/sys/book/saveOrUpdate"
            $.ajax({
                type: "POST",
                url: baseURL + url,
                contentType: "application/json",
                data: JSON.stringify(vm.book),
                success: function (r) {
                    if (r.code === 0) {
                        alert('操作成功', function () {
                            var page = $("#jqGrid").jqGrid('getGridParam', 'page');
                            $("#jqGrid").jqGrid('setGridParam', {
                                page: page
                            }).trigger("reloadGrid");
                            vm.showDom='list'
                        });
                    } else {
                        alert(r.msg);
                    }
                }
            });
        },
        getBook: function (id) {
            $.get(baseURL + "sys/book/findById/" + id, function (r) {
                vm.book = r.book;
            });
        },
        reload: function () {
            vm.showList = true;
            vm.showDom = 'list'

            var page = $("#jqGrid").jqGrid('getGridParam', 'page');
            $("#jqGrid").jqGrid('setGridParam', {
                postData: {
                    'bookname': vm.q.bookname
                },
                page: page
            }).trigger("reloadGrid");
        }
    }
});